import { useLocation } from "react-router-dom";
import { useEffect } from "react";
import {
  UploadOutlined,
  FolderAddOutlined,
  SearchOutlined,
  RedoOutlined,
  CloudUploadOutlined,
  DeleteOutlined,
  HomeOutlined,
} from "@ant-design/icons";
import {
  Button,
  message,
  Upload,
  Input,
  Table,
  Popconfirm,
  Breadcrumb,
  Menu,
  Dropdown,
} from "antd";
import { useState, useRef, forwardRef, useImperativeHandle } from "react";
import "./index.scss";
import UploadDrawer from "./components/UploadDrawer";
import AddFolderModal from "./components/AddFolderModal";
import { useSelector, useDispatch } from "react-redux";
import { useNavigate } from "react-router";
import UploadDragger from "./components/UploadDragger";

const PanTable = (props, ref) => {
  const location = useLocation();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  // 上传
  const uploadProps = props.uploadProps;
  const [isOpenUploadDraggerVisible, setOpenUploadDraggerVisible] =
    useState(false);
  const handleUploadDraggerModal = (isDirectory) => {
    if (isDirectory) {
      setUploadTitle("文件夹");
      setUploadDir(true);
    } else {
      setUploadTitle("文件");
      setUploadDir(false);
    }
    setOpenUploadDraggerVisible(true);
  };

  // 新建文件夹
  const hasAddFolder = props.hasAddFolder;
  const [isOpenAddFolderModal, setIsOpenAddFolderModal] = useState(false);
  const showAddFolderModal = () => {
    setIsOpenAddFolderModal(true);
  };
  const handleAddFolderOk = async (fetch) => {
    const res = await fetch();
    if (res.status !== 200) return message.error(res.msg);
    message.success(res.msg);
    fileList();
    setIsOpenAddFolderModal(false);
  };
  const handleAddFolderCancel = () => {
    setIsOpenAddFolderModal(false);
  };
  // 批量恢复
  const recoveDisabled = props.batchRecover?.disabled;
  const handleBatchRecover = props.batchRecover?.onClick;
  // 批量删除
  const deleteDisabled = props.batchDelete?.disabled;
  const handleBatchDelete = props.batchDelete?.onClick;
  // 搜索
  const handleSearch = props.search;
  // 刷新
  const hasRefresh = props.hasRefresh;
  /** 上传抽屉 */
  const hasUploadDrawer = props.hasUploadDrawer;
  const [isOpenUploadDLG, setOpenUpload] = useState(false);
  const [uploadTitle, setUploadTitle] = useState("上传文件");
  // 当前上传方式是否为上传文件夹
  const [isUploadDir, setUploadDir] = useState(false);
  const showUploadDrawer = () => {
    setOpenUpload(!isOpenUploadDLG);
  };
  // 返回上一级
  const searchParams = useSelector(
    (state) => state.searchReducer?.searchParams
  );
  const back = props.back;
  // 操作项
  const OperateItem = (row) => {
    const items = props.operateItem?.(row)?.map((item) => {
      if (item.key === "delete") {
        return (
          <Popconfirm
            title={item.title}
            onConfirm={item.onConfirm}
            okText="确定"
            cancelText="取消"
            key={item.key}
          >
            <a style={{ color: "red" }} href="#">
              {item.text}
            </a>
          </Popconfirm>
        );
      }
      return (
        <Button
          style={{ padding: "0 10px 0 0" }}
          key={item.key}
          type={item.type}
          disabled={item.disabled}
          onClick={item.onClick}
        >
          {item.text}
        </Button>
      );
    });
    return items;
  };
  const breadcurmbIndexTextMap = new Map([
    ["all", "全部"],
    ["pic", "图片"],
    ["doc", "文档"],
    ["video", "视频"],
    ["music", "音乐"],
    ["other", "其他"],
    ["bin", "回收站"],
  ]);
  // 表格
  const columns = props.columns?.map((item) => {
    if (item.key === "operate") {
      item.render = (text) => {
        return <OperateItem row={text}></OperateItem>;
      };
    }
    return item;
  });
  const [tableData, setTableData] = useState(props.dataSource);
  const [state, setState] = useState(
    Object.assign(
      {
        rowKey: "",
        rowSelection: {
          onChange: () => {},
        },
        pagination: {
          current: 1,
          size: 7,
          total: 0,
          showQuickJumper: true,
          onChange: () => () => {},
        },
        loading: false,
      },
      props.state
    )
  );
  const subfix = useRef("");
  const fileList = () => {
    state.loading = true;
    setState(state);
    setTimeout(async () => {
      const res =
        props.fetch && (await props.fetch({ subfix: subfix.current }));
      if (res) {
        setTableData(res.data);
        state.pagination.total = res.total;
      }
      state.loading = false;
      setState(state);
    }, 100);
  };
  useEffect(() => {
    const newSubfix = location.pathname.match(/[^/]*$/)[0];
    subfix.current = newSubfix;
    state.pagination.current = 1;
    setState(state);
    fileList();
  }, [location]);
  useImperativeHandle(ref, () => ({
    refreshTableList: fileList,
    showUploadDrawer,
  }));
  const handleBreadcrumb = (paths,searchPath, index) => {
    if (!searchPath) {
      navigate({ pathname: location.pathname });
    } else {
      const path = paths?.slice(0, index + 1)?.join('/');
      // const path = searchParams.path?.slice(
      //   1,
      //   searchParams.path?.lastIndexOf(`/${searchPath}`) + searchPath?.length + 1
      // );
      navigate({ pathname: location.pathname, search: `?path=/${path}` });
    }
  };
  const CustomBreadcrumb = () => {
    const paths = searchParams.path?.split("/")?.slice(1) || [];

    return (
      <Breadcrumb>
        <Breadcrumb.Item href="" onClick={handleBreadcrumb.bind(this, [], "")}>
          <HomeOutlined style={{ marginRight: "5px", fontSize: "15px" }} />
          {breadcurmbIndexTextMap.get(subfix.current)}
        </Breadcrumb.Item>
        {paths.map((item, index) => {
          return (
            <Breadcrumb.Item
              key={item}
              href=""
              onClick={handleBreadcrumb.bind(this, paths, item, index)}
            >
              <span>{item}</span>
            </Breadcrumb.Item>
          );
        })}
      </Breadcrumb>
    );
  };

  const uploadBtnMenu = () => {
    return (
      <Menu>
        <Menu.Item onClick={handleUploadDraggerModal.bind(this, false)}>
          上传文件
        </Menu.Item>
        <Menu.Item onClick={handleUploadDraggerModal.bind(this, true)}>上传文件夹</Menu.Item>
      </Menu>
    );
  };

  return (
    <div className="common-content-box">
      <div className="common-header">
        <div className="common-left-operate">
          {!!uploadProps ? (
            // <Upload {...uploadProps}>
            // <Button type="primary" icon={<UploadOutlined />}>
            //   上传
            // </Button>
            // </Upload>
            <Dropdown overlay={uploadBtnMenu} placement="bottom">
              <Button type="primary" icon={<UploadOutlined />}>
                上传
              </Button>
            </Dropdown>
          ) : (
            ""
          )}

          {hasAddFolder && subfix.current === "all" ? (
            <Button
              type="primary"
              icon={<FolderAddOutlined />}
              onClick={showAddFolderModal}
            >
              新建文件夹
            </Button>
          ) : (
            ""
          )}

          {!!handleBatchRecover ? (
            <Button
              type="primary"
              icon={<DeleteOutlined />}
              disabled={recoveDisabled}
              onClick={handleBatchRecover}
            >
              批量恢复
            </Button>
          ) : (
            ""
          )}

          {!!handleBatchDelete ? (
            <Button
              type="danger"
              icon={<DeleteOutlined />}
              disabled={deleteDisabled}
              onClick={handleBatchDelete}
            >
              批量删除
            </Button>
          ) : (
            ""
          )}
        </div>
        <div className="common-right-operate">
          {!!handleSearch ? (
            <Input
              placeholder="搜索您的文件"
              prefix={<SearchOutlined style={{ color: "gray" }} />}
              allowClear
              onChange={handleSearch}
            />
          ) : (
            ""
          )}
          {hasRefresh ? <RedoOutlined onClick={fileList} /> : ""}
          {hasUploadDrawer ? (
            <CloudUploadOutlined
              className={{ active: isOpenUploadDLG }}
              onClick={showUploadDrawer}
            />
          ) : (
            ""
          )}
        </div>
      </div>
      <div className="common-content">
        {/* <div className="common-position">
          <span>当前位置: </span>
          <span>{location.pathname} </span>
        </div> */}
        <div className="dir">
          <div className="breadcrumb">
            <CustomBreadcrumb></CustomBreadcrumb>
          </div>
          {/* {searchParams?.path ? (
            <Button type="link" onClick={back}>
              返回上一级
            </Button>
          ) : (
            ""
          )} */}
        </div>
        <div className="common-table">
          <Table {...state} dataSource={tableData} columns={columns}></Table>
        </div>
      </div>
      {/* 文件上传进度抽屉 */}
      <UploadDrawer
        isOpenUploadDLG={isOpenUploadDLG}
        setOpen={setOpenUpload}
      ></UploadDrawer>
      {/* 添加文件夹窗口 */}
      <AddFolderModal
        title="新建文件夹"
        isOpenAddFolderModal={isOpenAddFolderModal}
        onOk={handleAddFolderOk}
        onCancel={handleAddFolderCancel}
      ></AddFolderModal>
      {/* 拖拽上传文件窗口 */}
      <UploadDragger
        uploadProps={uploadProps}
        title={uploadTitle}
        isOpen={isOpenUploadDraggerVisible}
        setOpen={setOpenUploadDraggerVisible}
        isDirectory={isUploadDir}
        refreshTable={fileList}
      ></UploadDragger>
    </div>
  );
};
export default forwardRef(PanTable);
